package com.bysj.lms.controller;


import com.bysj.lms.common.ResultModel;
import com.bysj.lms.pojo.entity.DictionaryType;
import com.bysj.lms.service.IDictionaryTypeService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaojiakai
 * @since 2022-02-04
 */
@Slf4j
@Api(tags = "数据字典类型")
@RestController
@RequestMapping("/dictionary-type")
public class DictionaryTypeController {

    @Autowired
    IDictionaryTypeService dictionaryTypeService;

    @ApiOperation(value = "分页查询数据字典类型",notes = "name为空总查询，name不为空模糊查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页"),
            @ApiImplicitParam(name = "count",value = "页的大小"),
            @ApiImplicitParam(name = "name",value = "类型名")
    })
    @GetMapping("/find")
    public ResultModel find(Integer page, Integer count, String name){
        PageInfo pageInfo = dictionaryTypeService.findByPage(name, page, count);
        return ResultModel.success("查询成功",pageInfo);
    }


    @ApiOperation(value = "添加字典类型")
    @PostMapping("/add")
    public ResultModel add(@RequestBody DictionaryType dictionaryType){

        DictionaryType existOne = dictionaryTypeService.findByType(dictionaryType.getType());

        //不存在添加，存在已逻辑删除逻辑添加
        if(existOne == null){
            boolean save = dictionaryTypeService.save(dictionaryType);
            if(!save) return ResultModel.failure("添加失败");
        }else if(StringUtils.equals(existOne.getStatus(),"1")){
            boolean b = dictionaryTypeService.updateStatus(existOne.getId(), 0);
            if(!b) return ResultModel.failure("添加失败");
        }
        return ResultModel.success("添加成功");
    }

    @PutMapping("/update")
    @ApiOperation(value = "根据id更新")
    public ResultModel update(@RequestBody DictionaryType dictionaryType){
        boolean update = dictionaryTypeService.updateById(dictionaryType);
        if(update){
            return ResultModel.success("修改成功");
        }
        return ResultModel.failure("修改失败");
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "根据id删除",notes = "逻辑删除")
    public ResultModel delete(Integer id){
        boolean delete = dictionaryTypeService.updateStatus(id, 1);
        if(delete){
            return ResultModel.success("删除成功");
        }
        return ResultModel.success("删除失败");
    }
}

